package login.dao;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.DaoCommonHandler;
import game.db.DataSourceManager;

/**
 * 玩家货币消耗Dao
 * 
 * @author zhangning
 * 
 * @Date 2015年5月27日 下午7:29:28
 */
public class LogDomobIdfaDao {

	private static Logger logger = LoggerFactory.getLogger(LogDomobIdfaDao.class);

	private DataSource dataSource = DataSourceManager.getInstance().getDataSource();

	static class SingletonHolder {
		static LogDomobIdfaDao instance = new LogDomobIdfaDao();
	}

	public static LogDomobIdfaDao getInstance() {
		return SingletonHolder.instance;
	}

	/**
	 * 
	 * @param logCosts
	 * @return
	 */
	public void addLogIdfa(String appkey, String ifa, String ifamd5) {
		QueryRunner runner = new QueryRunner(dataSource);
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			runner.update(conn, "insert into domob_idfa(appkey,ifa,ifamd5) values(?,?,?)", appkey, ifa, ifamd5);
		} catch (SQLException e) {
			logger.error("", e);
		} finally {
			DbUtils.closeQuietly(conn);
		}
	}

	public boolean checkIdfaExist(String idfaStr) {
		String idfaMd5 = DigestUtils.md5Hex(idfaStr);
		boolean ret = false;
		QueryRunner runner = new QueryRunner(dataSource);
		try {
			ret = runner.query("SELECT EXISTS(select 1 from domob_idfa where ifa = ? or ifamd5 = ?)",
					DaoCommonHandler.Booleanhandler, idfaStr, idfaMd5);
		} catch (SQLException e) {
			logger.error("", e);
			return ret;
		}
		return ret;
	}

	public boolean isIdfaNoActive(String idfaStr) {
		String idfaMd5 = DigestUtils.md5Hex(idfaStr);
		boolean ret = false;
		QueryRunner runner = new QueryRunner(dataSource);
		try {
			ret = runner.query(
					"SELECT EXISTS(select 1 from domob_idfa where (ifa = ? or ifamd5 = ?) and is_active = 0)",
					DaoCommonHandler.Booleanhandler, idfaStr, idfaMd5);
		} catch (SQLException e) {
			logger.error("", e);
			return ret;
		}
		return ret;
	}

	public void setActive(String idfaStr) {
		String idfaMd5 = DigestUtils.md5Hex(idfaStr);
		QueryRunner runner = new QueryRunner(dataSource);
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			runner.update(conn, "update domob_idfa set is_active = 1 where ifa = ? or ifamd5 = ?", idfaStr, idfaMd5);
		} catch (SQLException e) {
			logger.error("", e);
		} finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public String getAppKey(String idfaStr){
		String idfaMd5 = DigestUtils.md5Hex(idfaStr);
		String ret = "";
		QueryRunner runner = new QueryRunner(dataSource);
		try {
			ret = runner.query("SELECT appkey from domob_idfa where ifa = ? or ifamd5 = ?",
					DaoCommonHandler.Stringhandler, idfaStr, idfaMd5);
		} catch (SQLException e) {
			logger.error("", e);
			return ret;
		}
		return ret;
	}

}
